import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import {Observable} from 'rxjs';
import {CommonService} from '@services/common.service';
import Utils from '@const/Utils';

@Injectable({
    providedIn: 'root'
})
export class AuthService implements CanActivate {

    constructor(private common: CommonService,
                private router: Router) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return new Promise(resolve => {
            this.common.checkUserSession(Utils.getUserInfo())
                .then(v => {
                    if (v) {
                        resolve(true);
                    } else {
                        this.router.navigateByUrl('/login');
                        resolve(false);
                    }
                });
        });
    }
}
